﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Navigation;
using Komunikator.Web;
using System.Diagnostics;
using System.ComponentModel.DataAnnotations;
using System.Windows.Data;

namespace Komunikator.Views
{
    public partial class EditAccount : Page
    {
        private User_Personal_Data userPersonalData;
        private RegistrationData registrationData = new RegistrationData();
        private ChangePasswordInfo changePasswordInfo = new ChangePasswordInfo();

        public EditAccount()
        {
            InitializeComponent();
            LayoutChangePassword2.DataContext = this.changePasswordInfo;
            UserPersonalDataSource.LoadedData += new EventHandler<LoadedDataEventArgs>(UserPersonalDataSource_LoadedData);
        }

        void UserPersonalDataSource_LoadedData(object sender, LoadedDataEventArgs e)
        {
            userPersonalData = (User_Personal_Data)e.Entities.FirstOrDefault();
        }

        // Executes when the user navigates to this page.
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
        }

        private void buttonSavePersonalData_Click(object sender, RoutedEventArgs e)
        {
            if (!Validation.GetHasError(tbAge))
            {
                busyIndicator.IsBusy = true;
                var context = (CommunicatorDomainContext)UserPersonalDataSource.DomainContext;
                if (context.HasChanges)
                {
                    var savePersonalData = context.SubmitChanges();
                    savePersonalData.Completed += (s, ve) =>
                        {
                            busyIndicator.IsBusy = false;
                        };
                }
                if (!UserPersonalDataSource.IsBusy)
                {
                    string oldCountryName = userPersonalData.Countries != null ? userPersonalData.Countries.CountryName : String.Empty;
                    string oldCityName = userPersonalData.Cities != null ? userPersonalData.Cities.CityName : String.Empty;

                    if (autoCompleteBoxCountry.Text != oldCountryName)
                    {
                        busyIndicator.IsBusy = true;
                        var loadCountries = context.Load(context.GetCountriesQuery());
                        loadCountries.Completed += new EventHandler(loadCountries_Completed);
                    }
                    else if (autoCompleteBoxCity.Text != oldCityName)
                    {
                        busyIndicator.IsBusy = true;
                        var loadCitites = context.Load(context.GetCitiesQuery());
                        loadCitites.Completed += new EventHandler(loadCitites_Completed);
                    }
                }
            }
        }

        void loadCountries_Completed(object sender, EventArgs e)
        {
            var context = (CommunicatorDomainContext)UserPersonalDataSource.DomainContext;

            //Check if country is empty
            if (autoCompleteBoxCountry.Text == String.Empty)
            {
                userPersonalData.Country = null;
            }
            else
            {
                //Check if country already exists in database
                if (!context.Countries.Any(c => c.CountryName == autoCompleteBoxCountry.Text))
                {
                    Countries country = new Countries();
                    country.CountryName = autoCompleteBoxCountry.Text;
                    context.Countries.Add(country);
                }
                userPersonalData.Country = context.Countries.Where(c => c.CountryName == autoCompleteBoxCountry.Text).FirstOrDefault().CountryId;
            }
            //If country has been changed city must be changed too
            var loadCitites = context.Load(context.GetCitiesQuery());
            loadCitites.Completed += new EventHandler(loadCitites_Completed);
        }

        void loadCitites_Completed(object sender, EventArgs e)
        {
            var context = (CommunicatorDomainContext)UserPersonalDataSource.DomainContext;

            //Check if city is empty
            if (autoCompleteBoxCity.Text == String.Empty)
            {
                userPersonalData.City = null;
            }
            else
            {
                if (!context.Cities.Any(c => c.CityName == autoCompleteBoxCity.Text && c.Countries.CountryName == autoCompleteBoxCountry.Text))
                {
                    Cities city = new Cities();
                    city.CityName = autoCompleteBoxCity.Text;
                    city.Country = context.Countries.Where(c => c.CountryName == autoCompleteBoxCountry.Text).FirstOrDefault().CountryId;
                    context.Cities.Add(city);
                }
                userPersonalData.City = context.Cities.Where(c => c.CityName == autoCompleteBoxCity.Text && c.Countries.CountryName == autoCompleteBoxCountry.Text).FirstOrDefault().CityId;
            }
            var saveUserCity = context.SubmitChanges();
            saveUserCity.Completed += (s, ev) =>
                {
                    if (saveUserCity.HasError)
                    {
                        MessageBox.Show("Błąd: " + saveUserCity.Error.Message);
                    }
                    busyIndicator.IsBusy = false;
                };
            
        }

        private void buttonSavePrivacySettings_Click(object sender, RoutedEventArgs e)
        {
            var context = (CommunicatorDomainContext)UserSettingsSource.DomainContext;
            if (context.HasChanges)
            {
                busyIndicatorChangeSettings.IsBusy = true;
                var saveUserSettings = context.SubmitChanges();
                saveUserSettings.Completed += (s, ev) =>
                    {
                        busyIndicatorChangeSettings.IsBusy = false;
                        if (!saveUserSettings.HasError)
                        {
                            MessageBox.Show("Ustawienia zostały zapisane!");
                        }
                        else
                        {
                            MessageBox.Show("Podczas zapisywania ustawień wystąpił błąd: "+saveUserSettings.Error.Message);
                        }
                    };
            }
        }

        private void ChangePasswordForm_AutoGeneratingField(object sender, DataFormAutoGeneratingFieldEventArgs e)
        {
            e.Field.Mode = DataFieldMode.AddNew;

            if (e.PropertyName == "OldPassword")
            {
                PasswordBox oldPasswordBox = (PasswordBox)e.Field.Content;
                this.changePasswordInfo.OldPasswordAccessor = () => oldPasswordBox.Password;
            }
            else if (e.PropertyName == "NewPassword")
            {
                PasswordBox newPasswordBox = (PasswordBox)e.Field.Content;
                this.changePasswordInfo.NewPasswordAccessor = () => newPasswordBox.Password;
            }
            else if (e.PropertyName == "PasswordConfirmation")
            {
                PasswordBox passwordConfirmationBox = (PasswordBox)e.Field.Content;
                this.changePasswordInfo.PasswordConfirmationAccessor = () => passwordConfirmationBox.Password;
            }
        }

        private void buttonChangePassword_Click(object sender, RoutedEventArgs e)
        {
            if (WebContext.Current.User.IsAuthenticated)
            {
                ChangePasswordBusyIndicator.IsBusy = true;
                var context = new CommunicatorDomainContext();
                var changePassword = context.UserChangePassword(WebContext.Current.User.Name, this.changePasswordInfo.OldPassword, this.changePasswordInfo.NewPassword);
                changePassword.Completed += (s, ev) =>
                {
                    ChangePasswordBusyIndicator.IsBusy = false;
                    if (!changePassword.HasError)
                    {
                        if (changePassword.Value)
                        {
                            MessageBox.Show("Hasło zostało zmienione");
                        }
                        else
                        {
                            MessageBox.Show("Wprowadzone stare hasło jest nieprawidłowe.");
                        }
                    }
                    else
                    {
                        MessageBox.Show("Wystąpił błąd: "+changePassword.Error.Message);
                    }
                };
            }
        }
    }
}
